package com.yd.mvc.pc.orderController;

import com.yd.app.service.pc.orderService.OrderService;
import com.yd.app.service.sys.UserService;
import com.yd.app.util.BusinessException;
import com.yd.app.util.ExcelUtil;
import com.yd.domain.business.Order;
import com.yd.domain.business.OrderCoupon;
import com.yd.domain.business.OrderDetial;
import com.yd.domain.business.OrderGoods;
import com.yd.domain.commom.PageModel;
import com.yd.domain.searchParam.OrderParam;
import com.yd.domain.sys.DicEnum;
import com.yd.domain.sys.User;
import com.yd.mvc.baseController.BaseController;
import com.yd.mvc.baseController.util.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 提交订单
 * Created by sunxianhui on 2018/3/7.
 */
@RestController
@RequestMapping(value = "/api/order")
public class OrderController extends BaseController {
    @Autowired
    OrderService orderService;
    @Value("${export.url}")
    private String export_url;
    @Value("${base.img.url}")
    private String base_image_url;
    @Autowired
    UserService userService;
    /**
     * 添加新订单
     * @param orderDetial
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Order addOrder(@RequestBody OrderDetial orderDetial) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.ORDER_MANAGER);//验证权限
        }
        Order order=new Order();
        List<OrderGoods> goods=orderDetial.getGoods();
        //添加订单商品信息
        for(int i=0;i<goods.size();i++){
            goods.get(i).setOrderId(order.getOrderId());
            goods.get(i).setCreateTime(new Date());
            orderService.addOrderGoods(goods.get(i));
        }
        //添加订单信息
        order.setIfCoupon(orderDetial.getIfCoupon());
        order.setDealPrice(orderDetial.getDealPrice());
        order.setTotalPrice(orderDetial.getTotalPrice());
        order.setCreateTime(new Date());
        int count= orderService.addOrder(order);
        //添加优惠券使用情况信息
        if(orderDetial.getIfCoupon()){
            OrderCoupon orderCoupon=new OrderCoupon();
            orderCoupon.setCouponId(orderDetial.getCouponId());
            orderCoupon.setOrderId(order.getOrderId());
            orderService.addOrderCoupon(orderCoupon);
        }

        if(count==1){
            return order;
        }else {
            throw new BusinessException(500, "添加订单信息失败");
        }
    }

    /**
     * 修改
     * @param order
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public void updateOrder(@RequestBody Order order) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.ORDER_MANAGER);//验证权限
        }
        orderService.updateOrder(order);
    }

    /**
     * 删除
     * @param id
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public void deleteOrder(@PathVariable("id") String id) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.ORDER_MANAGER);//验证权限
        }
        orderService.deleteOrderByid(id);
    }

    /**
     * 根据id查询
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/getOrder/{orderId}", method = RequestMethod.GET)
    public Order getOrder(@PathVariable("orderId") String orderId) {
        Order order = orderService.selectOrderById(orderId);
        if(order==null){
            order=new Order();
        }
        return order;
    }

    /**
     * 根据条件分页查询
     * @param orderParam
     * @param pageIndex
     * @param pageSize
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/getList/{pageIndex}/{pageSize}", method = RequestMethod.POST)
    public PageModel getOrderList(@RequestBody OrderParam orderParam, @PathVariable("pageIndex") int pageIndex, @PathVariable("pageSize") int pageSize) throws BusinessException {
        PageModel pageModel = null;
        try {
            pageModel = orderService.getOrderList(orderParam, pageIndex, pageSize);
        } catch (Exception e) {
            throw new BusinessException(500, "获取订单信息失败");
        }
        return pageModel;
    }

    /**
     * 根据orderId审核订单状态
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/reviewOrder/{orderId}/{status}", method = RequestMethod.GET)
    public void reviewOrder(@PathVariable("orderId") String orderId,@PathVariable("status") String status) {
        orderService.reviewOrder(orderId,status);
    }

    /**
     * 付款状态
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/payStatus/{orderId}/{payStatus}", method = RequestMethod.GET)
    public void payStatus(@PathVariable("orderId") String orderId,@PathVariable("payStatus") String payStatus) {
        orderService.payStatus(orderId,payStatus);
    }

    /**
     * 添加/修改物流快递单号
     * @param o
     * @return
     */
    @RequestMapping(value = "/addExpressCode", method = RequestMethod.POST)
    public void addExpressCode(@RequestBody Order o)  {
        orderService.addExpressCode(o);
    }

    /**
     * 导出订单
     */
    @RequestMapping(value = "/export/order/{orderId}", method = RequestMethod.GET)
    public void exportExcel(@PathVariable("orderId")String orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Order order = orderService.selectOrderById(orderId);
        User user=userService.getUserById(order.getUserId());
        if(order!=null){
            List<OrderGoods> goods=order.getGoods();
            if(goods!=null&&goods.size()>0){
                List<List<Object>> list=new ArrayList<>();
                List<Object> titleAll=new ArrayList<>();
                titleAll.add("姓名");
                titleAll.add("手机号");
                titleAll.add("公司名称");
                titleAll.add("货物总重量");
                list.add(titleAll);
                List<Object> liAll=new ArrayList<>();
                liAll.add(order.getUserName()+"");
                liAll.add(order.getPhone()+"");
                liAll.add(order.getCompanyName()+"");
                liAll.add(order.getTotalWeight()+"");
                list.add(liAll);

                List<Object> title=new ArrayList<>();
                title.add("序号");
                title.add("成色");
                title.add("编号");
                title.add("图片");
                title.add("名称");
                title.add("订单备注");
                title.add("单件重量");
                title.add("订货件数");
                title.add("总重量");
                list.add(title);
                int j=1;
                for(OrderGoods g:goods){
                    List<Object> li=new ArrayList<>();
                    li.add(j+"");
                    li.add(g.getTypeName()==null?"-":g.getTypeName());
                    li.add(g.getIdentifier()==null?"-":g.getIdentifier());
                    li.add(g.getIconUrl()==null?"-":base_image_url+g.getIconUrl());
                    li.add(g.getGoodsTitle()==null?"-":g.getGoodsTitle());
                    li.add(g.getContent()==null||g.getContent()==""?"-":g.getContent()+"("+g.getMinWeight()+"-"+g.getMaxWeight()+"克)");
                    float weight=(g.getMaxWeight()+g.getMinWeight())/2;
                    li.add(weight+"");
                    li.add(g.getDealNum()+"");
                    li.add(weight*g.getDealNum()+"");
                    list.add(li);
                    j++;
                }
                String path = this.getClass().getClassLoader().getResource("").getPath();
                String fileName="";
                if(user!=null){
                    fileName=user.getCompanyName()+"_"+user.getRealName()+"订单.xlsx";
                }else{
                    fileName=orderId+"订单.xlsx";
                }
                String path_temp=path.substring(1,path.length()-8)+"exportTemplate/order_template.xlsx";
                ExcelUtil.export2007Excel( list,path_temp, export_url,fileName);


                request.setCharacterEncoding("utf-8");
                downloadByUrl(response,export_url+fileName,fileName);
            }

        }

    }

    /**
     * 修改配货状态
     * @param goods
     */
    @RequestMapping(value = "/updatePhStatus", method = RequestMethod.PUT)
    public void updatePhStatus(@RequestBody OrderGoods goods) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.ORDER_MANAGER);//验证权限
        }
        orderService.updatePhStatus(goods);
    }
}
